package com.zds.support.adapter

import android.content.Context
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import com.zds.support.base.SupportBaseFragment

/**
 * FragmentPagerAdapter
 *
 *@Author zc
 *@Version V1.0
 **/
class AppFragmentPagerAdapter : FragmentPagerAdapter {
    private val data: ArrayList<Pair<String, Fragment>>

    companion object {

        private fun createData(fragments: List<Fragment>): ArrayList<Pair<String, Fragment>> {
            val data = ArrayList<Pair<String, Fragment>>()
            for (fragment in fragments) {
                data.add(Pair("", fragment))
            }
            return data
        }

        private fun createDataFromStringRes(context: Context, fragments: List<Pair<Int, Fragment>>): ArrayList<Pair<String, Fragment>> {
            val data = ArrayList<Pair<String, Fragment>>()
            for (pair in fragments) {
                val title = context.getString(pair.first)
                data.add(Pair(title, pair.second))
            }
            return data
        }
    }


    constructor(context: Context, fm: FragmentManager, data: List<Pair<Int, Fragment>>)
            : this(fm, createDataFromStringRes(context, data))

    constructor(fragments: List<Fragment>, fm: FragmentManager) : this(fm, createData(fragments))

    constructor(fm: FragmentManager, data: ArrayList<Pair<String, Fragment>>) : super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
        this.data = data
    }

    private var mChildCount = 0
    override fun getItem(position: Int): Fragment {
        return data[position].second
    }

    private var isHasChanged = false
    override fun notifyDataSetChanged() {
        mChildCount = getCount();
        isHasChanged = true
        super.notifyDataSetChanged()
    }

    override fun getItemPosition(`object`: Any): Int {
        if (mChildCount > 0) {
            mChildCount--;
            return POSITION_NONE;
        }
        /* if (isHasChanged){
             return POSITION_NONE;

         }*/
        return super.getItemPosition(`object`)
    }

    override fun getItemId(position: Int): Long {
        val fragment = data[position].second
        if (fragment is SupportBaseFragment) {
            return fragment.fragmentId.toLong()
        }
        return super.getItemId(position)
    }

    override fun getCount(): Int = data.size

    override fun getPageTitle(position: Int): CharSequence {
        return data[position].first
    }
}